package com.qhs.upload.controller;

import com.qhs.framework.utils.Result;
import com.qhs.upload.service.OSSUploadService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by zano on 2017/3/20.
 */
@Controller
@RequestMapping(value = {"sysUpload"})
public class OSSUploadController {
    @Autowired
    private OSSUploadService ossUploadService;

    @RequestMapping(value = "/uploadImg", method= RequestMethod.POST)
    @ResponseBody
    public Result uploadImage(HttpServletRequest request, MultipartFile file){
        String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        if(!"jpg".equals(type) && !"png".equals(type) && !"jpeg".equals(type)){
            return new Result(false,"请上传jpg,png,jpeg类型的图片");
        }else {
            try {
                String uploadImg = ossUploadService.uploadImg(file);
                String[] split = uploadImg.split("\\?");
                String imgUrl = split[0].toString();
                return new Result(true, "上传成功", imgUrl);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,"上传失败");
            }
        }
    }

    @RequestMapping(value = "/download")
    public void download(String fileUrl, String fileName, HttpServletResponse response)throws IOException{
        OutputStream os = response.getOutputStream();
        try {
            response.reset();//清空response的buffer
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-disposition",
                    "inline; filename=\"" +  new String(fileName.getBytes("gbk"),
                            "ISO8859-1" )  + "\"");
            os.write(FileUtils.readFileToByteArray(new File(fileUrl)));
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (os != null) {
                os.close();
            }
        }
    }


}
